<template>
  <div style="padding-left:10px; padding-right: 10px; width: calc(100vw - 200px)">
    <!--    搜索区域-->
    <div style="margin: 10px 0">
      <span style="color: #611ee3;font-size: large;">课程名：</span>
      <el-input v-model="search" placeholder="请输入课程名" style="width: 20%" clearable></el-input>
      <el-button style="margin-left: 5px; background-color: #409EFF; color: white" @click="load" plain>查询</el-button>
    </div>
    <el-table
        :data="tableData"
        border
        stripe
        style="width: 100%">
      <el-table-column
          prop="id"
          label="ID"
          sortable>
      </el-table-column>
      <el-table-column
          prop="courseName"
          label="课程名">
      </el-table-column>
      <el-table-column
          label="课程封面">
        <template #default="scope">
          <div class="demo-image__preview">
            <el-image
                style="width: 100px; height: 100px"
                :src="scope.row.courseImg"
                :preview-src-list="[scope.row.courseImg]">
            </el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column
          prop="courseInfo"
          label="课程信息">
      </el-table-column>
      <el-table-column
          prop="coursePrice"
          label="单价">
      </el-table-column>
      <el-table-column
          label="课程状态">
        <template #default="scope">
          <span v-if="scope.row.courseStatus==='1'">未开始</span>
          <span v-if="scope.row.courseStatus==='2'">进行中</span>
          <span v-if="scope.row.courseStatus==='3'">已结束</span>
        </template>
      </el-table-column>
      <el-table-column
          label="操作">
        <template #default="scope">
          <div style="display: flex; align-content: space-between">
            <el-button @click="deleteStatus(scope.row)" type="primary">购买</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin: 10px 0">
      <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage4"
          :page-sizes="[5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
      <el-dialog
          title="提示"
          v-model="deleteVisible"
          width="35%">
        <p style="margin-bottom: 40px;font-size: 17px;color: #f73c3c;">请先选择教练：</p>
        <!--        <template>-->
        <div>
          <el-radio-group style="margin-bottom: 40px;font-size: 17px;" v-model="coachId" @change="changeRadio">
            <el-radio v-for="opt in tableData1" :key="opt.id" :label="opt.id">
              <a @click="getCoach(opt.id)" style="font-size: 17px;font-weight: 500;opacity: 0.8;text-decoration: underline"> {{ opt.userName }}</a>
            </el-radio>
          </el-radio-group>
        </div>
        <!--        </template>-->
        <span slot="footer" class="dialog-footer">
          <el-button @click="this.deleteVisible = false">取 消</el-button>
          <el-button type="primary" @click="addCourseBuy(this.coachId)">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog
          title="提示"
          v-model="coachFlag"
          width="35%">
        <el-form ref="form" :model="form1" label-width="90px" disabled="true">
          <el-form-item label="教练名">
            <el-input v-model="form1.userName" disabled></el-input>
          </el-form-item>
          <el-form-item label="年龄">
            <el-input v-model="form1.age"></el-input>
          </el-form-item>
          <el-form-item label="性别">
            <el-radio v-model="form1.sex" label="男">男</el-radio>
            <el-radio v-model="form1.sex" label="女">女</el-radio>
            <el-radio v-model="form1.sex" label="未知">未知</el-radio>
          </el-form-item>
          <el-form-item label="专业特长">
            <el-input type="textarea" v-model="form1.major" ></el-input>
          </el-form-item>
          <el-form-item label="电话">
            <el-input v-model="form1.phone"></el-input>
          </el-form-item>
          <el-form-item label="备注">
            <el-input type="textarea" v-model="form1.remark" ></el-input>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>


import request from "@/utils/request";
import XLSX from "xlsx";

export default {
  name: 'course',
  components: {},
  data() {
    return {
      form: {},
      search: '',
      currentPage4: 1,
      pageSize: 10,
      total: 0,
      tableData: [],
      user: {},
      deleteVisible: false,
      coachId: '',
      tableData1: [],
      openFlag: true,
      price: 0,
      member:{},
      flag:true,
      coachFlag:false,
      form1:{}
    }
  },
  created() {
    this.load();
    let Str = sessionStorage.getItem("member") || '{}';
    this.member = JSON.parse(Str);
    let userStr = sessionStorage.getItem("user") || '{}';
    this.user = JSON.parse(userStr);
    // let Str1 = sessionStorage.getItem("coach") || '{}';
    // this.form1 = JSON.parse(Str1);
//请求后端服务器，确认当前登录用户的合法性
    request.get("/api/user/" + this.user.id).then(res => {
      if (res.code === '0') {
        this.user = res.data;
      }
    });
  },
  methods: {
    load() {
      request.get("/api/course", {
        params: {
          pageNum: this.currentPage4,
          pageSize: this.pageSize,
          search: this.search
        }
      }).then(res => {
        console.log(res);
        this.tableData = res.data.records;
        this.total = res.data.total;
      })
    },
    changeRadio(item) {
      console.log(item)
    },
    loadCoach() {
      request.get("/api/coach", {
        params: {
          pageNum: this.currentPage4,
          pageSize: this.pageSize,
          search: this.search
        }
      }).then(res => {
        console.log(res);
        this.tableData1 = res.data.records;
      })
    },
    getCoach(coachId){
      this.coachFlag=true;
      console.log(coachId)
       request.get("/api/coach/getCoachById", {
        params: {
          coachId: coachId
        }
      }).then(res => {
         this.form1 =res.data[0]
      });
    },
    deleteStatus(row) {
      this.deleteVisible = true;
      this.form = JSON.parse((JSON.stringify(row)));
      this.loadCoach();
    },
    handleSizeChange(pageSize) {//改变当前页面个数
      this.pageSize = pageSize;
      this.load();
    },
    handleCurrentChange(pageNum) {//改变当前页码
      this.currentPage4 = pageNum;
      this.load();
    },
    async addCourseBuy() {
      this.openFlag = true;
      this.flag=true;
      if (this.coachId === '') {
        this.$message({
          message: '必须选择教练!',
          type: 'warning'
        });
      } else {
        const params = {
          coachId: this.coachId,
          courseId: this.form.id,
          memberId: this.member.id
        }
        await request.get("/api/consumRecord/getCourseCopy", {
          params: {
            courseId: this.form.id,
            memberId: this.member.id
          }
        }).then(res => {
          console.log(res.data)
          if (res.data.length > 0) {
            this.$message({
              message: '该课程已购买!',
              type: 'warning'
            });
            this.openFlag = false;
            this.deleteVisible = false;//关闭弹窗
          }
        });
        if (this.openFlag) {
          await request.get("/api/member/findMemberId", {
            params: {
              id: this.member.id
            }
          }).then(res => {
            if (res.data[0].balance < this.form.coursePrice) {
              this.$message({
                message: '会员卡余额不足，请前往个人中心充值!',
                type: 'warning'
              });
              this.flag=false;
              this.deleteVisible = false;//关闭弹窗
            }

            // sessionStorage.setItem("member",JSON.stringify(res.data[0]));
            // this.form=res.data[0]
            // //页面重新加载
            // // location.reload();
          });
          if (this.flag){
            await request.post("/api/consumRecord", params).then(res => {
              if (res.code === '0') {
                this.$message({
                  type: "success",
                  message: "购买成功"
                })
              } else {
                this.$message({
                  type: "error",
                  message: res.msg
                })
              }
              this.load();//刷新表格数据
              this.deleteVisible = false;//关闭弹窗
            });
          }

        }
      }
    },
    handleDelete(id) {
      console.log(id);
      // request.delete("/api/course/"+id).then(res => {
      //   if (res.code==='0'){
      //     this.$message({
      //       type: "success",
      //       message: "删除成功"
      //     })
      //   }else {
      //     this.$message({
      //       type: "error",
      //       message: res.msg
      //     })
      //   }
      //   this.deleteVisible = false;//关闭弹窗
      //   this.load()//重新加载
      // });
    },

    filesUploadSuccess(res) {
      console.log(res);
      this.form.courseImg = res.data;
      this.load();
    }

  }
}
</script>
